package com.shanhai.wallpapers.network.request

import com.shanhai.wallpapers.network.exception.ApiException
import org.json.JSONObject
import retrofit2.Response

abstract class ApiRequest {
    suspend fun <T : Any> apiRequest(apiCall: suspend () -> Response<T>): T {
        try {
            val response = apiCall.invoke()
            if (response.isSuccessful) {
                return requireNotNull(response.body())

            } else {
                val errorBodyString = response.getErrorBodyString()
                errorBodyString?.let {
                    val errorBodyJson = JSONObject(it)
                    throw ApiException(
                        errorBodyJson.getString("error") ?: "unknown error has occurred"
                    )
                } ?: throw ApiException("${response.code()}: ${response.message()}")
            }

        } catch (exception: Exception) {
            throw ApiException("Oops! an error occurred.\n${exception.localizedMessage}")
        }
    }

    private fun Response<*>.getErrorBodyString(): String? {
        return errorBody()?.string()
    }
}